// $Id: memory.cpp 2 2009-09-02 08:47:42Z joseph2002 $
/*
 * Copyright 2009 Joseph Wu
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
 *
 * For more information, see http://xpcomplus.sourceforge.net
 */

#define XPCOM_SOURCE

#include <xpcom/config.hpp>
#include <cstring> // for memcpy
#include <xpcom/exception.hpp>
#include <xpcom/memory.hpp>
#include "api/xpcom.hpp"

namespace xpcom {

void* memory::alloc_data(size_t size)
{
    void* p = ::NS_Alloc(size);
    if (!p)
        throw_bad_alloc();
    return p;
}

void* memory::alloc_data_nothrow(size_t size) throw()
{
    return ::NS_Alloc(size);
}

void* memory::realloc_data(void* ptr, size_t size)
{
    void* p = ::NS_Realloc(ptr, size);
    if (!p && size != 0) // realloc returns NULL if size is 0
        throw_bad_alloc();
    return p;
}

void* memory::realloc_data_nothrow(void* ptr, size_t size) throw()
{
    return ::NS_Realloc(ptr, size);
}

void memory::free_data(void* ptr) throw()
{
    ::NS_Free(ptr);
}

void* memory::clone_data(const void* ptr, size_t size)
{
    if (!ptr)
        return 0;

    void* p = alloc_data(size);
    std::memcpy(p, ptr, size);
    return p;
}

void* memory::clone_data_nothrow(const void* ptr, size_t size) throw()
{
    if (!ptr)
        return 0;

    void* p = alloc_data_nothrow(size);
    if (p)
        std::memcpy(p, ptr, size);
    return p;
}

} // namespace xpcom
